package com.fasteat.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasteat.common.entity.GlobalException;
import com.fasteat.common.entity.Result;
import com.fasteat.mall.entity.BoughtHistory;
import com.fasteat.mall.entity.Orderform;
import com.fasteat.mall.entity.Product;
import com.fasteat.mall.entity.vo.OrderformProductVo;
import com.fasteat.mall.entity.vo.NewOrderformVo;
import com.fasteat.mall.mapper.OrderformMapper;
import com.fasteat.mall.service.BoughtHistoryService;
import com.fasteat.mall.service.OrderformService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasteat.mall.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hy
 * @since 2021-01-19
 */
@Service
public class OrderformServiceImpl extends ServiceImpl<OrderformMapper, Orderform> implements OrderformService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ProductService productService;

    @Autowired
    private BoughtHistoryService boughtHistoryService;

    @Override
    @Transactional
    public boolean CustomerBuy(NewOrderformVo orderformVo) {
        if(orderformVo == null) {
            throw new GlobalException(Result.error("请勿添加空订单"));
        }
        if(orderformVo.getProductId() == null) {
            throw new GlobalException(Result.error("请添加商品Id"));
        }
        Integer purchaseAmount = orderformVo.getPurchaseAmount();
        Product product = productService.getById(orderformVo.getProductId());
        if(product.getInventory() - purchaseAmount < 0 || product.getInventory() < 0) {
            throw new GlobalException(Result.error("库存不足"));
        }
        //生成要生成的订单
        Orderform orderform = new Orderform();
        orderform.setAftersalesStatus(0);
        orderform.setOrderStatus(1);
        orderform.setAddressId(orderformVo.getAddressId());
        orderform.setProductId(orderformVo.getProductId());
        orderform.setUserId(orderformVo.getUserId());
        orderform.setPurchaseAmount(purchaseAmount);
        int ret1 = baseMapper.insert(orderform);
        if(ret1 != 1) {
            throw new GlobalException(Result.error("添加订单失败"));
        }
        //修改商品库存及销量
        product.setInventory(product.getInventory() - purchaseAmount);
        product.setSalesVolume(product.getSalesVolume() + purchaseAmount);
        boolean ret2 = productService.updateById(product);
        if(ret2 != true) {
            throw new GlobalException(Result.error("修改库存失败"));
        }
        //将该商品加入购买过的商品表
        BoughtHistory boughtHistory = new BoughtHistory();
        boughtHistory.setUserId(orderformVo.getUserId());
        boughtHistory.setProductId(orderformVo.getProductId());
        boughtHistory.setSalesVolume(product.getSalesVolume());
        boughtHistory.setSort(product.getSort());
        boughtHistoryService.save(boughtHistory);
        return true;
    }

    @Override
    public List<OrderformProductVo> pageVoIAmAngry(Integer start, Integer end, Integer orderformStatus, String userId) {
        if (!orderformStatus.equals(1)
                && !orderformStatus.equals(2)
                && !orderformStatus.equals(3)
                && !orderformStatus.equals(4)
                && !orderformStatus.equals(5)
        ) {
            throw new GlobalException(Result.error("请输入正确的类型"));
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id", userId);
        wrapper.eq("order_status", orderformStatus);
        List<Orderform> orderformList = baseMapper.selectList(wrapper);
        //对start和end进行保护
        int size = orderformList.size();
        if(size == 0 || start > size) {
            return null;
        }
//        if() {
//
//        }
        end = end > size ? size : end;
        List<OrderformProductVo> retList = new ArrayList<>();
        for(Orderform orderform : orderformList) {
            Product product = productService.getById(orderform.getProductId());
            OrderformProductVo orderformProductVo = new OrderformProductVo();
            //封装商品信息
            orderformProductVo.setTitle(product.getTitle());
            orderformProductVo.setAvatar(product.getAvatar());
            orderformProductVo.setSalePrice(product.getSalePrice());
            //封装订单信息
            orderformProductVo.setId(orderform.getId());
            orderformProductVo.setUserId(orderform.getUserId());
            orderformProductVo.setProductId(orderform.getProductId());
            orderformProductVo.setPurchaseAmount(orderform.getPurchaseAmount());
            orderformProductVo.setAddressId(orderform.getAddressId());
            orderformProductVo.setOrderStatus(orderform.getOrderStatus());
            orderformProductVo.setAftersalesStatus(orderform.getAftersalesStatus());
            orderformProductVo.setGmtCreate(orderform.getGmtCreate());
            orderformProductVo.setGmtModified(orderform.getGmtModified());
            //打入retList
            retList.add(orderformProductVo);
        }
        retList.add(null);
        //切割
        List<OrderformProductVo> retListCopy = retList.subList(start, end);
        return retListCopy;
    }

//    /**
//     * 申请退款
//     *
//     * @param aftersalesDto
//     */
//    @Override
//    public void refund(AftersalesDto aftersalesDto) {
//        if(StringUtils.isEmpty(aftersalesDto.getOrderFormId())) {
//            throw new GlobalException(Result.error("id为空"));
//        }
//        Orderform orderform = baseMapper.selectById(aftersalesDto.getOrderFormId());
//        if(orderform.getAftersalesStatus().equals(1) ||
//                orderform.getAftersalesStatus().equals(2) ||
//                orderform.getAftersalesStatus().equals(3) ||
//                orderform.getAftersalesStatus().equals(4) ||
//                orderform.getAftersalesStatus().equals(5) ||
//                orderform.getAftersalesStatus().equals(6)) {
//            throw new GlobalException(Result.error("此订单正在处理中或已处理完毕"));
//        }
//        Map<String, String> mapParent = new HashMap<>();
//        mapParent.put("orderFormId", aftersalesDto.getOrderFormId());
//        mapParent.put("reason", aftersalesDto.getReason());
//        mapParent.put("Img", aftersalesDto.getImg());
//        mapParent.put("userId", aftersalesDto.getUserId());
//        if(orderform.equals(null)) {
//            throw new GlobalException(Result.error("查无此订单"));
//        }
//        //修改为申请退款状态
//        orderform.setAftersalesStatus(1);
//        int ret = baseMapper.updateById(orderform);
//        if(ret != 1) {
//            throw new GlobalException(Result.error("修改订单状态失败"));
//        }
//        redisTemplate.opsForList().rightPush("refund", mapParent);
//    }
//
//    /**
//     * 申请退货
//     *
//     * @param aftersalesDto
//     */
//    @Override
//    public void returnGoods(AftersalesDto aftersalesDto) {
//        if(StringUtils.isEmpty(aftersalesDto.getOrderFormId())) {
//            throw new GlobalException(Result.error("id为空"));
//        }
//        Orderform orderform = baseMapper.selectById(aftersalesDto.getOrderFormId());
//        if(orderform.getAftersalesStatus().equals(1) ||
//                orderform.getAftersalesStatus().equals(2) ||
//                orderform.getAftersalesStatus().equals(3) ||
//                orderform.getAftersalesStatus().equals(4) ||
//                orderform.getAftersalesStatus().equals(5) ||
//                orderform.getAftersalesStatus().equals(6)) {
//            throw new GlobalException(Result.error("此订单正在处理中或已处理完毕"));
//        }
//        Map<String, String> mapParent = new HashMap<>();
//        mapParent.put("orderFormId", aftersalesDto.getOrderFormId());
//        mapParent.put("reason", aftersalesDto.getReason());
//        mapParent.put("Img", aftersalesDto.getImg());
//        mapParent.put("userId", aftersalesDto.getUserId());
//        if(orderform.equals(null)) {
//            throw new GlobalException(Result.error("查无此订单"));
//        }
//        //修改为申请退货状态
//        orderform.setAftersalesStatus(2);
//        int ret = baseMapper.updateById(orderform);
//        if(ret != 1) {
//            throw new GlobalException(Result.error("修改订单状态失败"));
//        }
//        redisTemplate.opsForList().rightPush("returnGoods", mapParent);
//    }
//
//    /**
//     * 申请换货
//     *
//     * @param aftersalesDto
//     */
//    @Override
//    public void exchangeGoods(AftersalesDto aftersalesDto) {
//        if(StringUtils.isEmpty(aftersalesDto.getOrderFormId())) {
//            throw new GlobalException(Result.error("id为空"));
//        }
//        Orderform orderform = baseMapper.selectById(aftersalesDto.getOrderFormId());
//        if(orderform.getAftersalesStatus().equals(1) ||
//                orderform.getAftersalesStatus().equals(2) ||
//                orderform.getAftersalesStatus().equals(3) ||
//                orderform.getAftersalesStatus().equals(4) ||
//                orderform.getAftersalesStatus().equals(5) ||
//                orderform.getAftersalesStatus().equals(6)) {
//            throw new GlobalException(Result.error("此订单正在处理中或已处理完毕"));
//        }
//        Map<String, String> mapParent = new HashMap<>();
//        mapParent.put("orderFormId", aftersalesDto.getOrderFormId());
//        mapParent.put("reason", aftersalesDto.getReason());
//        mapParent.put("Img", aftersalesDto.getImg());
//        mapParent.put("userId", aftersalesDto.getUserId());
//        if(orderform.equals(null)) {
//            throw new GlobalException(Result.error("查无此订单"));
//        }
//        //修改为申请换货状态
//        orderform.setAftersalesStatus(3);
//        int ret = baseMapper.updateById(orderform);
//        if(ret != 1) {
//            throw new GlobalException(Result.error("修改订单状态失败"));
//        }
//        redisTemplate.opsForList().rightPush("exchangeGoods", mapParent);
//    }
//
//    /**
//     * 查看退款申请
//     *
//     * @return
//     */
//    @Override
//    public List<AftersalesDto> queryRefund() {
//        Long size = redisTemplate.opsForList().size("refund");
//        List<Map<String, String>> refundList = (ArrayList<Map<String, String>>) redisTemplate.opsForList().range("refund", 0, size);
//        if (refundList.size() == 0) {
//            // 无退款申请
//            return null;
//        }
//        int cur = 0;
//        List<AftersalesDto> aftersalesDtoList = new ArrayList<>();
//        while(cur < size) {
//            Map<String, String> mapSon = refundList.get(cur);
//            cur++;
//            AftersalesDto aftersalesDto = new AftersalesDto(mapSon.get("userId"), mapSon.get("orderFormId"), mapSon.get("reason"), mapSon.get("img"));
//            aftersalesDtoList.add(aftersalesDto);
//        }
//        return aftersalesDtoList;
//    }
//
//    /**
//     * 查看退货申请
//     *
//     * @return
//     */
//    @Override
//    public List<AftersalesDto> queryReturnGoods() {
//        Long size = redisTemplate.opsForList().size("returnGoods");
//        List<Map<String, String>> refundList = (ArrayList<Map<String, String>>) redisTemplate.opsForList().range("returnGoods", 0, size);
//        if (refundList.size() == 0) {
//            // 无退款申请
//            return null;
//        }
//        int cur = 0;
//        List<AftersalesDto> aftersalesDtoList = new ArrayList<>();
//        while(cur < size) {
//            Map<String, String> mapSon = refundList.get(cur);
//            cur++;
//            AftersalesDto aftersalesDto = new AftersalesDto(mapSon.get("userId"), mapSon.get("orderFormId"), mapSon.get("reason"), mapSon.get("img"));
//            aftersalesDtoList.add(aftersalesDto);
//        }
//        return aftersalesDtoList;
//    }
//
//    /**
//     * 查看换货申请
//     *
//     * @return
//     */
//    @Override
//    public List<AftersalesDto> queryExchangeGoods() {
//        Long size = redisTemplate.opsForList().size("exchangeGoods");
//        List<Map<String, String>> refundList = (ArrayList<Map<String, String>>) redisTemplate.opsForList().range("exchangeGoods", 0, size);
//        if (refundList.size() == 0) {
//            // 无退款申请
//            return null;
//        }
//        int cur = 0;
//        List<AftersalesDto> aftersalesDtoList = new ArrayList<>();
//        while(cur < size) {
//            Map<String, String> mapSon = refundList.get(cur);
//            cur++;
//            AftersalesDto aftersalesDto = new AftersalesDto(mapSon.get("userId"), mapSon.get("orderFormId"), mapSon.get("reason"), mapSon.get("img"));
//            aftersalesDtoList.add(aftersalesDto);
//        }
//        return aftersalesDtoList;
//    }
//
//    @Override
//    public void processRefund(AfterSalesProcessDto afterSalesProcessDto, Boolean result) {
//        Orderform orderform = baseMapper.selectById(afterSalesProcessDto.getUserId());
//        if(result) {
//            orderform.setAftersalesStatus(4);
//        } else {
//            orderform.setAftersalesStatus(7);
//        }
//        redisTemplate.opsForList().leftPop("refund");
////        NotifyClient.宏志哥的接口();
//    }
//
//    @Override
//    public void processReturn(AfterSalesProcessDto afterSalesProcessDto, Boolean result) {
//        Orderform orderform = baseMapper.selectById(afterSalesProcessDto.getUserId());
//        if(result) {
//            orderform.setAftersalesStatus(5);
//        } else {
//            orderform.setAftersalesStatus(7);
//        }
//        redisTemplate.opsForList().leftPop("refund");
////        NotifyClient.宏志哥的接口();
//    }
//
//    @Override
//    public void processExchange(AfterSalesProcessDto afterSalesProcessDto, Boolean result) {
//        Orderform orderform = baseMapper.selectById(afterSalesProcessDto.getUserId());
//        if(result) {
//            orderform.setAftersalesStatus(6);
//        } else {
//            orderform.setAftersalesStatus(7);
//        }
//        redisTemplate.opsForList().leftPop("refund");
////        NotifyClient.宏志哥的接口();
//    }
}
